package com.stock.stockana.requests;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.stock.stockana.beans.ResponseBean;
import com.stock.stockana.constants.NetWorkConstants;
import com.stock.stockana.events.network.LoginInEvent;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * Created by ljgsonx on 2016/1/24.
 */
public class LoginIn extends BaseStringRequest<LoginIn> {

    private final static String TAG = "LoginIn--->";
    private String userName;
    private String userPwd;

    private LoginIn() {
        super(Method.POST, NetWorkConstants.LOGIN_URL, listener, errorListener);
        Log.d(TAG, NetWorkConstants.LOGIN_URL);
    }

    static Response.Listener<String> listener = new Response.Listener<String>(){

        @Override
        public void onResponse(String response) {
            try{
                ResponseBean rb = JSON.parseObject(response, ResponseBean.class);
                EventBus.getDefault().post(new LoginInEvent(rb));
            }catch (Exception e) {
                ResponseBean rb = new ResponseBean();
                rb.setRespCode(NetWorkConstants.RESPONSE_CODE_ERROR);
                rb.setErrorMsg(NetWorkConstants.RESPONSE_ERROR1 + response);
                EventBus.getDefault().post(new LoginInEvent(rb));
            }
        }
    };

    static Response.ErrorListener errorListener = new Response.ErrorListener(){

        @Override
        public void onErrorResponse(VolleyError error) {
            ResponseBean rb = new ResponseBean();
            rb.setRespCode(NetWorkConstants.RESPONSE_CODE_NETWORK_ERROR);
            rb.setErrorMsg(NetWorkConstants.RESPONSE_ERROR3 + error.toString());
            EventBus.getDefault().post(new LoginInEvent(rb));
        }
    };

    @Override
    protected Map<String, String> getParams() throws AuthFailureError {
        Map<String, String> map = new HashMap<>();
        map.put("userName", userName);
        map.put("userPwd", userPwd);
        return map;
    }

    public static LoginIn build() {
        return new LoginIn();
    }

    public LoginIn setUserNameAndPwd(String userName,String userPwd) {
        this.userName = userName;
        this.userPwd = userPwd;
        return this;
    }

}
